package com.fezs.web.mvc.interceptor;

import cn.hutool.core.util.StrUtil;
import com.fezs.common.context.BaseContextHandler;
import com.fezs.common.utils.TraceIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhukai
 * @since 2022/8/18
 */
@Slf4j
public class TraceIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        this.putTraceId(request);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        this.clearTraceId(response);
    }

    /**
     * 放入traceId
     */
    private void putTraceId(HttpServletRequest request) {
        String traceId = request.getHeader(BaseContextHandler.TRACEID);
        traceId = StrUtil.isEmpty(traceId) ? TraceIdUtils.putTraceId() : traceId;
        if (StrUtil.isNotEmpty(traceId)) {
            MDC.put(BaseContextHandler.TRACEID, traceId);
            BaseContextHandler.setTraceId(traceId);
        }
    }

    /**
     * 清除traceId
     */
    private void clearTraceId(HttpServletResponse response) {
        response.setHeader(BaseContextHandler.TRACEID, MDC.get(BaseContextHandler.TRACEID));
        MDC.remove(BaseContextHandler.TRACEID);
        BaseContextHandler.remove();
    }

}
